package cn.wzvtc.ch12pagesort.controller;

import cn.wzvtc.ch12pagesort.entity.User;
import cn.wzvtc.ch12pagesort.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    //分页
    @GetMapping("/listPage")
    public Page<User> listPage() {
        Pageable pageable = PageRequest.of(0, 20, Sort.Direction.DESC, "id");
        Page<User> userPage = userRepository.findAll(pageable);
        return userPage;
    }

    @GetMapping("/findPageByGender")
    public Page<User> findPageByGender(Integer gender) {
        Pageable pageable = PageRequest.of(0, 20);
        Page<User> userPage = userRepository.findPageByGender(gender, pageable);
        return userPage;
    }

    //排序
    @GetMapping("/listSort")
    public List<User> listSort() {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return userRepository.findAll(sort);
    }

    @GetMapping("/findByGenderSort")
    public List<User> findByGenderSort(Integer gender) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        List<User> users = userRepository.findByGenderSort(gender, sort);
        return users;
    }

    @GetMapping("/listSort1")
    public List<User> listSort1() {
        Sort sort = Sort.by(Sort.Direction.DESC, "age", "id");
        return userRepository.findAll(sort);
    }
}
